<?php
/**
 * Basic benchmarking class to record the time between Benchmark::time() calls.
 *
 * Only one instance can exist of this class. (Singleton)
 *
 * This class is incomplete. It should be extending Singleton, however due to limitations of the
 * current PHP version used on the live versions this can not be done.
 * Should extend Singleton as soon as possible.
 *
 * @author daantimmer
 *
 * @package Library
 */

/**
 * A class to make benchmarking the PHP scripts more easy.
 *
 * @author daantimmer
 */
class Benchmark{
	
	/**
	 * Array to hold all the timed calls of Benchmark::time();
	 *
	 * @see Benchmark::time()
	 * @var mixed
	 */
	private static $times = array();
	
	/**
	 * Temporary value for holding the previous unix timestamp
	 * @var integer
	 */
	private static $prev = 0;
	
	/**
	 * Used for Singleton functionality.
	 * Only one instance of Benchmark may exist at all times
	 * @var Benchmark
	 */
	private static $instances = null;
	
	/**
	 * Protected constructor.
	 * @return void
	 */
	protected function __construct(){
		self::$prev = Util::getMicrotime();
		self::$times = array();
		self::time();
	}
	
	/**
	 * Creates a new instance of Benchmark if no instance was found. Else returns current instance.
	 *
	 * @return Benchmark
	 */
	final public static function instance(){
		$class_name = __CLASS__;

		if (!isset(self::$instances))
		self::$instances = new $class_name;

		return self::$instances;
	}
	
	/**
	 *
	 * @return integer
	 */
	final public static function time(){
		$bt = debug_backtrace();
		$class = $bt[1]["class"];
		$func = $bt[1]["function"];
		$line = $bt[0]["line"];
		
		$time = Util::getMicrotime();
		$delta = $time-self::$prev;
		self::$prev = $time;
		self::$times[] = "{$class}::{$func}({$line}): {$delta}s";
		
		return $time;
	}
	
	final public function getTimes(){
		return self::$times;
	}
	
	final public static function sGetTimes(){
		return self::$times;
	}
}